import requests, urllib, json
from mysqldb.models import AllinpayWxchatPos

import logging

logger = logging.getLogger(__name__)

# wxAppsConf = {
#     "appid": "wxd2ba909c0fdb075c",  # appID
#     "secret": "132a00946ac75f66fd696802b0b91a78",
#     "host": "https://open.weixin.qq.com",
#     "rect": "http://ppt.3vppt.com/api/wxRect",
#     "scope": "snsapi_userinfo",  # "snsapi_base",#"snsapi_userinfo"
# }

from requests.packages.urllib3.exceptions import InsecureRequestWarning

# 禁用安全请求警告
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)


class wxAppsRequest(requests.Session):
    """微信小程序SDK"""

    host = "https://api.weixin.qq.com"

    def __init__(self, wxConf=1):
        super().__init__()
        self.CONF = self.hasConf(wxConf)

    def hasConf(self, idx=1):
        """查询配置"""
        try:
            r = AllinpayWxchatPos.objects.get(id=idx)
        except BaseException as err:
            return None
        else:
            return r

    def hasToken(self):
        """获取token 返回:{
        "access_token":"ACCESS_TOKEN",
        "expires_in":7200
        }"""
        url = "/cgi-bin/token"
        headers = {"Content-Type": "application/json"}
        params = {
            "appid": self.CONF.apps_appid,  # wxConf["appid"],
            "secret": self.CONF.apps_secret,  # wxConf["secret"],
            "grant_type": "client_credential",
        }
        # params = json.dumps(params, ensure_ascii=False).encode("utf8")
        r = self.do_get(url, headers=headers, params=params)
        return r

    def codeLogin(self, code):
        """
        小程序登录  返回:
        {
            "openid":"xxxxxx",
            "session_key":"xxxxx",
            "unionid":"xxxxx",
            "errcode":0,
            "errmsg":"xxxxx"
        }
        """
        url = "/sns/jscode2session"
        headers = {"Content-Type": "application/json"}
        params = {
            "appid": self.CONF.apps_appid,  # wxConf["appid"],
            "secret": self.CONF.apps_secret,  # wxConf["secret"],
            "js_code": code,
            "grant_type": "authorization_code",
        }
        # params = json.dumps(params, ensure_ascii=False).encode("utf8")
        r = self.do_get(url, headers=headers, params=params)
        return r

    def do_get(self, url="", headers=None, params=None, data=None):
        url = self.host + url
        try:
            r = self.get(url, headers=headers, params=params, data=data, verify=False)
            return r.json() if r and r.status_code == 200 else {}
        except BaseException as err:
            logger.error(f"[微信小程序] GET请求失败 {err}")
            return {}

    def do_post(self, url="", headers=None, params=None, data=None, json=None):
        url = self.host + url
        try:
            r = self.post(
                url, headers=headers, params=params, data=data, json=json, verify=False
            )
            # logger.info(f"[微信小程序] POST请求失败 {r.text}")
            return r.json() if r and r.status_code == 200 else {}
        except BaseException as err:
            logger.error(f"[微信小程序] POST请求失败 {err}")
            return {}

    def hasMyQrCode(self, share):
        """获取推广二维码"""
        tk = self.hasToken()
        if not tk:
            raise BaseException("请求Token失败!")
        url = "/wxa/getwxacodeunlimit"
        header = {"Content-Type": "application/json"}
        params = {"access_token": tk.get("access_token")}
        data = {
            "page": "pages/AppLoading/AppLoading",
            "scene": f"share={share}",
            "check_path": False,
        }
        data = json.dumps(data, ensure_ascii=False).encode("utf8")
        r = self.post(
            self.host + url, headers=header, params=params, data=data, verify=False
        )
        return r
